package com.frxuexi.park2302.park

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.frxuexi.lib_base.entity.ParkBean
import com.frxuexi.lib_base.entity.ParkBeanItem
import com.frxuexi.lib_base.entity.Res
import com.frxuexi.lib_base.http.ApiService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext

class ParkDataSource(val apiService: ApiService,val para:String,val reqType:String):PagingSource<Int,ParkBeanItem>() {
    override fun getRefreshKey(state: PagingState<Int, ParkBeanItem>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ParkBeanItem> {
        return withContext(Dispatchers.IO){
            try {
                val page=params.key?:1
                val list = mutableListOf<ParkBeanItem>()
                var res:Res<ParkBean>?=null
                var res2:Res<ParkBeanItem>?=null
                if(reqType=="类型"){
                    res = apiService.getParkByType(para).first()
                    list.addAll(res.data)
                }else if(reqType=="区域"){
                    res = apiService.getParkByArea(para.toInt()).first()
                    list.addAll(res.data)
                }else if(reqType=="状态"){
                    res = apiService.getParkByStatus(para).first()
                    list.addAll(res.data)
                }else if(reqType=="车牌号"){
                    res2 = apiService.getParkByCarNo(para).first()
                    list.add(res2.data)
                }

                if (res?.code==200 || res2?.code==200){
                    LoadResult.Page(list.sortedByDescending { it.id },null,null)
                }else{
                    LoadResult.Error(Exception(res?.message?:res2?.message))
                }
            }catch (e:Exception){
                LoadResult.Error(e)
            }
        }
    }
}